//
//  YZYSaccountStore.m
//  Candy2
//
//  Created by Aiwa on 11/2/15.
//  Copyright © 2015 Aiwa. All rights reserved.
//

#import "YZYSaccountStore.h"
#import "YZYSDKManager.h"
#import "UIView+Toast.h"
#import "YZYSDKManagerHeader.h"
#import "MBProgressHUD.h"

static YZYSaccountStore* instanceOnce = nil;
static YZYSaccountStore* instanceOnce;

@interface YZYSaccountStore()

@end

@implementation YZYSaccountStore

+ (YZYSaccountStore*)sharedInstance{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instanceOnce = [[self alloc] init];
    });
    return instanceOnce;
}

- (void)saveAccessToken:(NSString*) accessToken
{
    [[NSUserDefaults standardUserDefaults] setObject:accessToken forKey:@"accessToken"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
- (NSString*)getAccessToken
{
    return [[NSUserDefaults standardUserDefaults] objectForKey:@"accessToken"];
}
- (void)removeAccessToken
{
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"accessToken"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)saveUserInfoStr:(NSString*)userInfoStr
{
    [[NSUserDefaults standardUserDefaults] setObject:userInfoStr forKey:@"userInfoStr"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
- (NSString*)getUserInfoStr
{
    return [[NSUserDefaults standardUserDefaults] objectForKey:@"userInfoStr"];
}
- (void)removeUserInfoStr
{
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"userInfoStr"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)saveUserIdentifier:(NSString*)userIdentifier
{
    [[NSUserDefaults standardUserDefaults] setObject:userIdentifier forKey:@"userIdentifier"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
- (NSString*)getUserIdentifier
{
    return [[NSUserDefaults standardUserDefaults] objectForKey:@"userIdentifier"];
}
- (void)removeUserIdentifier
{
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"userIdentifier"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)saveIsScoreOpen:(BOOL) isScoreOpen
{
    [[NSUserDefaults standardUserDefaults] setBool:isScoreOpen forKey:@"isScoreOpen"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
- (BOOL)getIsScoreOpen
{
    return [[NSUserDefaults standardUserDefaults] boolForKey:@"isScoreOpen"];
}

- (void)saveAgreeSelected:(BOOL)isSelected {
    [[NSUserDefaults standardUserDefaults] setBool:isSelected forKey:@"agreeSelected"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
- (BOOL)getAgreeSelected {
    return [[NSUserDefaults standardUserDefaults] boolForKey:@"agreeSelected"];
}

- (void)reLogin {
    //清除登录信息
    [[YZYSaccountStore sharedInstance] removeAccessToken];
    [[YZYSaccountStore sharedInstance] removeUserInfoStr];
    [[YZYSaccountStore sharedInstance] removeUserIdentifier];
    
    //返回登录页
    [[YZYSDKManager shareManager] yzy_showLoginUI];
}

#pragma mark - 得到时间戳字符串
+ (NSString *)getTsString
{
    NSDate * now = [NSDate date];
    NSTimeInterval diff = [now timeIntervalSince1970];
    NSString * diffString = [NSString stringWithFormat:@"%ld",(long)diff];
    return diffString;
}

- (void)getCurrentWindowWithCompletion:(void (^)(UIWindow *window))completion {
    if ([NSThread isMainThread]) {
        // 如果已经在主线程上，直接执行
        UIWindow *keyWindow = [self findCurrentWindow];
        if (completion) {
            completion(keyWindow);
        }
    } else {
        // 如果不在主线程上，调度到主线程
        dispatch_async(dispatch_get_main_queue(), ^{
            UIWindow *keyWindow = [self findCurrentWindow];
            if (completion) {
                completion(keyWindow);
            }
        });
    }
}

- (UIWindow *)findCurrentWindow {
    UIWindow *keyWindow = nil;
    NSArray *windows = [UIApplication sharedApplication].windows;

    // 反向遍历窗口数组，寻找符合条件的窗口
    for (UIWindow *window in [windows reverseObjectEnumerator]) {
        if ([window isKindOfClass:[UIWindow class]] && CGRectEqualToRect(window.bounds, [UIScreen mainScreen].bounds) && ![window isKindOfClass:NSClassFromString(@"UITextEffectsWindow")]) {
            keyWindow = window;
            break;  // 找到符合条件的窗口后退出循环
        }
    }

    // 如果没有找到符合条件的窗口，则从所有窗口中寻找 keyWindow
    if (keyWindow == nil) {
        keyWindow = [windows objectAtIndex:0];  // 初始化为第一个窗口
        for (UIWindow *window in windows) {
            if (window.isKeyWindow) {
                keyWindow = window;
                break;  // 找到 keyWindow 后退出循环
            }
        }
    }

    return keyWindow;
}

- (void)makeToastFromWindow:(NSString *)message {
    [self getCurrentWindowWithCompletion:^(UIWindow *window) {
        if (window) {
            [window makeToast:message];
        }
    }];
}

- (void)makeAlertViewFromWindow:(NSString *)message {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    //添加取消按钮
    UIAlertAction* cancelBtn = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) {
    }];
    [alert addAction:cancelBtn];
    //显示
    [self getCurrentWindowWithCompletion:^(UIWindow *window) {
        if (window) {
            UIViewController *curViewController = window.rootViewController;
            [curViewController presentViewController:alert animated:YES completion:nil];
        }
    }];
}

- (UIImage *)getImage:(NSString *)imageStr {
    if (YZY_IS_APPLE) {
        UIImage *image = [UIImage imageNamed:imageStr];
        return image;
    } else {
        NSBundle *bundle = [NSBundle bundleWithPath:[[NSBundle bundleForClass:[self class]] pathForResource:@"YZYSDK" ofType:@"bundle"]];
        NSString *imagePath = [bundle pathForResource:[NSString stringWithFormat:@"%@@3x", imageStr] ofType:@"png"];
        UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
        return image;
    }
}

//获取当前时间戳
- (NSString *)currentTimeStr {
    NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];//获取当前时间0秒后的时间
    NSTimeInterval time=[date timeIntervalSince1970];// *1000 是精确到毫秒，不乘就是精确到秒
    NSString *timeString = [NSString stringWithFormat:@"%.0f", time];
    return timeString;
}

//根据颜色生成图片
- (UIImage*)imageWithColor:(UIColor*)color
{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}

- (void)showHUDAddedToWindow {
    [self getCurrentWindowWithCompletion:^(UIWindow *window) {
        if (window) {
            MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:window];
            hud.removeFromSuperViewOnHide = YES;
            [window addSubview:hud];
            [hud showAnimated:YES];
        }
    }];
}

- (void)hideHUDForWindow {
    [self getCurrentWindowWithCompletion:^(UIWindow *window) {
        if (window) {
            MBProgressHUD *hud = [MBProgressHUD HUDForView:window];
            if (hud != nil) {
                hud.removeFromSuperViewOnHide = YES;
                [hud hideAnimated:YES];
            }
        }
    }];
}

@end
